<?php

class AjaxController extends Application_Model_Controller
{
    protected $jsonData = array();

    public function init()
    {
        // TODO проверять на валидность данные в каждом экшене!!!
        if ($this->getRequest()->isXmlHttpRequest()) {
            Zend_Controller_Action_HelperBroker::removeHelper('viewRenderer');
            $this->_helper->layout->disableLayout();
        }
    }

    public function newprofitAction()
    {
        $summ = $this->getRequest()->getParam('summ');
        $date = $this->getRequest()->getParam('date');
        $mapper = new Application_Model_Mapper('Application_Model_DbTable_Profits', new Application_Model_Profit());
        $res = $mapper->insert(array(
            'profit_summ' => $summ,
            'profit_date' => $date
        ));

        if ($res) {
           $this->jsonData['status'] = 'ok';
           return true;
        } else {
            $this->jsonData['status'] = 'no_insert';
            return false;
        }
    }

    public function savedebtAction()
    {
        $id         = $this->getRequest()->getParam('debt_id');
        $summ       = $this->getRequest()->getParam('summ');
        $name       = urldecode($this->getRequest()->getParam('name'));
        $type       = $this->getRequest()->getParam('type_debt');
        $dateDebt   = $this->getRequest()->getParam('date_debt');
        $dateReturn = $this->getRequest()->getParam('date_return');
        $mapper = new Application_Model_DebtMapper();

        if (!$id) {
            $rest = $mapper->insert(array(
                    'debt_summ'   => $summ,
                    'name_debter' => $name,
                    'type_debt'   => $type,
                    'date_debt'   => $dateDebt,
                    'date_return' => $dateReturn,
                )
            );

            return $this->jsonData['status'] = $rest;
        }

        $where['debt_id = ?'] = $id;
        $res = $mapper->update(array(
                'debt_summ'   => $summ,
                'name_debter' => $name,
                'type_debt'   => $type,
                'date_debt'   => $dateDebt,
                'date_return' => $dateReturn,
            ), $where
        );

        if ($res) {
            $this->jsonData['status'] = 'ok';
            return true;
        }

        $this->jsonData['status'] = 'error';
        return false;
    }

    public function editprofitAction()
    {
        $id   = $this->getRequest()->getParam('id');
        $summ = $this->getRequest()->getParam('summ');
        $date = $this->getRequest()->getParam('date');
        $mapper = new Application_Model_Mapper('Application_Model_DbTable_Profits', new Application_Model_Profit());

        if ($id) {
            $where['profit_id = ?'] = $id;

            $res = $mapper->update(
                array(
                    'profit_summ' => $summ,
                    'profit_date' => $date
                ),
                $where
            );
        } else {
            $res = $mapper->insert(
                array(
                    'profit_summ' => $summ,
                    'profit_date' => $date
                )
            );
        }

        if ($res) {
            $this->jsonData['status'] = 'success';
            return true;
        } else {
            $this->jsonData['status'] = 'error';
            return false;
        }
    }

    public function deleteAction()
    {
        $id = $this->getRequest()->getParam('id');
        $type = $this->getRequest()->getParam('type');

        switch ($type) {
            case 'debt':
                $mapper = new Application_Model_DebtMapper();
                $field = 'debt_id';

                break;
            case 'profit':
                $field = 'profit_id';
                $mapper = new Application_Model_ProfitMapper();
                break;
        }

        $result = false;
        if (isset($mapper) && isset($field))  {
            $result = $mapper->del($field, $id);
        }

        if ($result) {
            $this->jsonData['status'] = 'ok';
            return true;
        }

        $this->jsonData['status'] = 'error';
        return false;
    }

    public function geteditprofitAction()
    {
        $id = $this->getRequest()->getParam('id');

        if (!$id) {
            $profit = new Application_Model_Profit();
        } else {
            $mapper = new Application_Model_ProfitMapper();
            $profit = $mapper->getById($id);

            if (!$profit) {
                $profit = new Application_Model_Profit();
            }
        }

        $this->view->profit = $profit;
        $this->render('editprofit');
    }

    public function geteditdebtAction()
    {
        $id = $this->getRequest()->getParam('id');

        if (!$id) {
            $debt = new Application_Model_Debt();
        } else {
            $mapper = new Application_Model_Mapper('Application_Model_DbTable_Debts', new Application_Model_Debt());
            $debt = $mapper->getById($id);
        }

        if (!$debt) {
            $debt = new Application_Model_Debt();
        } else {
            $this->jsonData['id'] = $debt->getDebtId();
        }

        $this->view->debt = $debt;
        $this->jsonData['html'] = $this->view->render('/ajax/editdebt.phtml');
    }

    public function postDispatch()
    {
        if ($this->jsonData) {
            header('Content-type: text/json');
            header('Content-type: application/json');
            echo Zend_Json::encode($this->jsonData);
        }
    }

    public function getformAction()
    {
        $id   = $this->_getParam('id');
        $type = $this->_getParam('type');

        if (!$id || !$type) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $form = new Application_Model_Form($id, $type);
        $this->jsonData['html'] = $form->render();
        return true;
    }

    public function createtermAction()
    {
        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Terms(), new Application_Model_Term());
        $this->jsonData['type']   = 'add';
        $this->jsonData['result'] = 'ok';
        $termId = $mapper->insert(array());
        $this->jsonData['id'] = $termId;
    }

    public function savetermAction()
    {
        $optionsTerm = array();
        $optionsTerm['term_name']    = $this->getRequest()->getParam('name_term', '');
        $optionsTerm['first_symbol'] = $this->getRequest()->getParam('first_symbol', '');
        $termId = $this->getRequest()->getParam('term_id', '');
        $optionsTerm['term_info']    = $this->_getParam('info', '');
        $term = new Application_Model_Term($optionsTerm);
        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Terms(), $term);


        if ($termId) {
            $mapper->updateTerm($optionsTerm, $termId);
        } else {
            $termId = $mapper->insertTerm($optionsTerm);
        }

        $this->jsonData['result'] = 'ok';
        $this->jsonData['term_id'] = $termId;

    }

    public function addtagAction()
    {
        $name   = $this->getRequest()->getParam('tag', '');
        $termId = $this->getRequest()->getParam('term_id', false);

        if ($name) {
            $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Tags(), new Application_Model_Tag());
            $tag = $mapper->getTagByName($name);

            if (!$tag || !$tag->getTagId()) {
                $id  = $mapper->insert(array('tag_name'=> $name));
                $tag = new Application_Model_Tag(array('tag_id' => $id, 'tag_name' => $name));
            }

            $this->jsonData['tag_id'] = $tag->getTagId();

            if ($termId) {
                $mapperStudy = new Application_Model_StudyMapper(new Application_Model_DbTable_Terms(), new Application_Model_Term());
                //TODO сначала проверить нет ли уже такого тега у этого термина
                $mapperStudy->updateTerm(array(), $termId, array($tag->getTagId()));
            }

            $this->jsonData['result'] = 'ok';
            return true;
        } else {
            $this->jsonData['result'] = 'error';
            return false;
        }

    }

    public function deletetermAction()
    {
        $id = $this->getRequest()->getParam('term_id');

        if (!$id) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Terms, new Application_Model_Term());
        $mapper->deleteTerm($id);
        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function getdebtsAction()
    {
        $type = $this->_getParam('type');
        $mapper = new Application_Model_DebtMapper();
        $debts = $mapper->getDebtsByType($type);

        if (!$debts) {
            $this->jsonData['status'] = 'no_debts';
            $this->view->debt = new Application_Model_Debt();
            $this->jsonData['html'] = $this->view->render('/ajax/editdebt.phtml');
            return false;
        }

        $this->view->debts = $debts;
        $this->render('debts');
        return true;
    }

    public function getprofitsAction()
    {
        $period = (int) $this->getRequest()->getParam('period', Application_Model_ProfitMapper::LIMIT_PROFITS_DEFAULT);
        $mapper = new Application_Model_ProfitMapper();
        $json = $mapper->getDataForHightCharts($period);
        $this->jsonData['profits'] = $json;
    }

    public function getstudytagsAction()
    {
        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Tags(), new Application_Model_Tag());
        $tags = $mapper->getTags();
        $this->jsonData['tags'] = $tags;
    }

    public function deletetagAction()
    {
        $TermId = $this->getRequest()->getParam('term_id');
        $TagId = $this->getRequest()->getParam('tag');
        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_TermsToTags(), new Application_Model_Tag());
        $rest = $mapper->deleteTagFromTerm($TermId, $TagId);

        if ($rest) {
            $this->jsonData['result'] = 'ok';
        } else {
            $this->jsonData['result'] = 'error';
        }

    }

    public function creategoodAction()
    {
        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Buy(), new Application_Model_Buy());
        $buyId = $mapper->insert(array());
        $this->jsonData['id'] = $buyId;
    }

    public function deletegoodAction()
    {
        $id = $this->getRequest()->getParam('id');

        if (!$id) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Buy, new Application_Model_Buy());
        $mapper->del('buy_id', $id);
        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function savebuyAction()
    {
        $id    = $this->getRequest()->getParam('id');
        $type  = $this->getRequest()->getParam('type');
        $title = $this->getRequest()->getParam('title');
        $desc  = $this->getRequest()->getParam('desc');
        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Buy, new Application_Model_Buy());
        $mapper->update(
            array(
                'buy_name' => $title,
                'buy_type' => $type,
                'buy_description' => $desc,
            ),'buy_id = '. (int) $id
        );
        $this->jsonData['result'] = 'ok';
    }

    public function buytopAction()
    {
        $id     = $this->getRequest()->getParam('id');
        $status = $this->getRequest()->getParam('status');

        if (!$id || !isset($status)) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Buy, new Application_Model_Buy());

        if ($status == Application_Model_Buy::UP_TOP) {
            $status = (int) $mapper->getById($id)->getBuyStatus() + 1;
            $status++;
        }

        if ($status == Application_Model_Buy::DOWN_TOP) {
            $status = (int) $mapper->getById($id)->getBuyStatus() - 1;
        }
        $mapper->update(
            array(
                'buy_status' => $status,
            ), 'buy_id = '. (int) $id
        );

        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function createtaskAction()
    {
        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Tasks(), new Application_Model_Task());
        $this->jsonData['id'] = $mapper->insert(array('task_limit' => $this->_getParam('task_limit', Application_Model_Task::CURRENT)));
        $this->jsonData['result'] = 'ok';
    }

    public function savetaskAction()
    {
        $options = $this->getRequest()->getParam('params', array());
        $taskId = $options['task_id'];
        $options['task_date'] = date('Y-m-d H:i:s');
        unset($options['task_id']);
        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Tasks(), new Application_Model_Task());
        $mapper->update($options, 'task_id = ' . $taskId);
        $this->jsonData['result'] = 'ok';
        $this->jsonData['task_id'] = $taskId;
    }

    public function  deletetaskAction()
    {
        $id = (int) $this->getRequest()->getParam('task_id');

        if (!$id) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_IdeaMapper();
        $mapper->del('task_id', $id);
        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function tasktoarchiveAction()
    {
        $id = (int) $this->getRequest()->getParam('task_id');

        if (!$id) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_IdeaMapper();
        $mapper->update(array('task_status' => Application_Model_Task::STATUS_ARCHIVE), 'task_id = ' . $id);
        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function savenoteAction()
    {
        $noteId = $this->_getParam('id');
        $title  = $this->_getParam('title');
        $type   = $this->_getParam('type');

        $options = array(
            'note_title' => $title,
            'note_type'  => $type,
            'note_date'  => date('Y-m-d H:i:s'),
        );

        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Notes(), new Application_Model_Note());
        $mapper->update($options, 'note_id = ' . $noteId);
        $this->jsonData['result']  = 'ok';
        $this->jsonData['note_id'] = $noteId;
    }

    public function createnoteAction()
    {
        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Notes(), new Application_Model_Note());
        $this->jsonData['id'] = $mapper->insert(array());
        $this->jsonData['result'] = 'ok';
    }

    public function deletenoteAction()
    {
        $id = (int) $this->_getParam('note_id');

        if (!$id) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Notes(), new Application_Model_Note());
        $mapper->del('note_id', $id);
        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function setactiontermAction()
    {
        $termId = (int) $this->_getParam('term_id');
        $action = (int) $this->_getParam('term_action');
        $mapper = new Application_Model_StudyMapper(new Application_Model_DbTable_Terms(), new Application_Model_Term());
        return $mapper->update(array('term_in_action' => $action), 'term_id = ' . $termId);
    }

    public function createtravelAction()
    {
        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Travels(), new Application_Model_Travel());
        $this->jsonData['id'] = $mapper->insert(array());
        $this->jsonData['result'] = 'ok';
    }

    public function savetravelAction()
    {
        $id     = $this->getRequest()->getParam('id');
        $status = $this->getRequest()->getParam('status');
        $title  = $this->getRequest()->getParam('title');
        $desc   = $this->getRequest()->getParam('desc');

        $bind = array();

        if ($title) {
            $bind['title'] = $title;
        }

        if ($desc) {
            $bind['desc'] = $desc;
        }

        if ($status) {
            $bind['status'] = $status;
        }

        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Travels(), new Application_Model_Travel());
        $mapper->update($bind, 'id = '. (int) $id);
        $this->jsonData['result'] = 'ok';
    }

    public function deletetravelAction()
    {
        $id = (int) $this->_getParam('id');

        if (!$id) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_Travels(), new Application_Model_Travel());
        $mapper->del('id', $id);
        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function addtodigestAction()
    {
        $objectId = $this->_getParam('object_id');
        $typeId = $this->_getParam('type_id');

        if (!($objectId && $typeId)) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $mapper = new Application_Model_Mapper(new Application_Model_DbTable_MainTask(), Application_Model_Thing::getModelByType($typeId));
        $mapper->insert(
            array(
            'object_id' => $objectId,
            'type'   => $typeId,
        ));

        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function deletedigestAction()
    {
        $objectId = $this->_getParam('object_id');
        $typeId = $this->_getParam('type_id');

        if (!($objectId && $typeId)) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        $table = new Application_Model_DbTable_MainTask();
        $table->fetchRow($table->select()->where('object_id = ?', $objectId)->where('type = ?' , $typeId))->delete();
        $this->jsonData['result'] = 'ok';
        return true;
    }

    public function savesortAction()
    {
        $serialize = $this->_getParam('table-digest');

        if (!$serialize) {
            $this->jsonData['result'] = 'error';
            return false;
        }

        Application_Model_Thing::saveSortDataDigest($serialize);
        $this->jsonData['result'] = 'ok';
        return true;
    }
}
